package com.fizzkai.p2p.website.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fizzkai.p2p.core.util.AjaxResult;
import com.fizzkai.p2p.core.util.UserContext;
import com.fizzkai.p2p.website.util.RequireLogin;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(handler);
        System.out.println(handler.getClass());
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method.hasMethodAnnotation(RequireLogin.class)) {
                // 判断 是否有登陆
                if (UserContext.getCurrentLoginInfo() == null) {
                    return unLogin(method, response);
                }
            }
        }
        return true;
    }
    // 未登录
    private boolean unLogin (HandlerMethod method, HttpServletResponse response) throws Exception{
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(new ObjectMapper().writeValueAsString(new AjaxResult("用户未登录，请登录再试",false)));
            return false;
        }
        response.sendRedirect("/login.html");
        return false;
    }
}
